'use strict'

const { Role, Op } = require('../model');

async function getAll(ctx, next) {
    let keyword = ctx.request.query.keyword;
    console.log(keyword);
    let res = {}
    if (keyword) {
        res = await Role.findAll({
            where: {
                [Op.or]: [
                    {
                        rolename: {
                            [Op.substring]: keyword
                        }
                    },
                    {
                        email: {
                            [Op.substring]: keyword
                        }
                    }
                ]
            }
        });
    } else {
        res = await Role.findAll();
    }
    ctx.body = res;

}
async function getById(ctx, next) {
    let id = ctx.request.params.id;
    let data = await Role.findByPk(id);

    ctx.body = {
        code: 1000,
        data: data,
        msg: '查询指定项目成功'
    }
}
async function addItem(ctx, next) {
    let obj = ctx.request.body;
    let res = await Role.create({
        rolename: obj.rolename,
        email: obj.email
    })
    ctx.body = {
        code: 1000,
        data: null,
        msg: '新增成功'
    }
}
async function updateItem(ctx, next) {
    let id = ctx.request.params.id;
    let obj = ctx.request.body;
    await Role.update({ rolename: obj.rolename, email: obj.email }, {
        where: {
            id: id
        }
    });

    ctx.body = {
        code: 1000,
        data: null,
        msg: '修改成功'
    }
}
async function delItem(ctx, next) {
    let id = ctx.request.params.id;
    await Role.destroy({
        where: {
            id: id
        }
    });
    ctx.body = {
        code: 1000,
        data: null,
        msg: '删除成功'
    }
}
// async function getAll(ctx, next) {

// }

module.exports = {
    'get /roles': getAll,
    'get /roles/:id': getById,
    'post /roles': addItem,
    'put /roles/:id': updateItem,
    'del /roles/:id': delItem,
}